<?php

namespace app\common\library;

use think\Exception;

/**
 * 微信模板消息推送工具类
 */
class WechatMessage
{
    protected $appId;
    protected $appSecret;
    protected $accessToken;
    protected $accessTokenExpire;

    public function __construct()
    {
        // 从配置文件或数据库获取微信配置
        $this->appId = config('wechat.app_id') ?: '';
        $this->appSecret = config('wechat.app_secret') ?: '';
    }

    /**
     * 获取访问令牌
     */
    protected function getAccessToken()
    {
        // 检查缓存中的access_token是否有效
        $cacheKey = 'wechat_access_token';
        $accessToken = cache($cacheKey);
        
        if ($accessToken && $accessToken['expire'] > time()) {
            return $accessToken['token'];
        }

        // 重新获取access_token
        $url = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid={$this->appId}&secret={$this->appSecret}";
        
        $response = $this->httpGet($url);
        $result = json_decode($response, true);
        
        if (isset($result['access_token'])) {
            $accessToken = [
                'token' => $result['access_token'],
                'expire' => time() + $result['expires_in'] - 300 // 提前5分钟过期
            ];
            
            cache($cacheKey, $accessToken, $result['expires_in'] - 300);
            return $accessToken['token'];
        } else {
            throw new Exception('获取微信access_token失败：' . json_encode($result));
        }
    }

    /**
     * 发送模板消息
     */
    public function sendTemplateMessage($openid, $templateId, $data, $url = '', $miniprogram = [])
    {
        if (empty($openid)) {
            throw new Exception('openid不能为空');
        }

        $accessToken = $this->getAccessToken();
        $apiUrl = "https://api.weixin.qq.com/cgi-bin/message/template/send?access_token={$accessToken}";
        
        $message = [
            'touser' => $openid,
            'template_id' => $templateId,
            'data' => $data
        ];
        
        if ($url) {
            $message['url'] = $url;
        }
        
        if (!empty($miniprogram)) {
            $message['miniprogram'] = $miniprogram;
        }
        
        $response = $this->httpPost($apiUrl, json_encode($message));
        $result = json_decode($response, true);
        
        if ($result['errcode'] == 0) {
            return true;
        } else {
            throw new Exception('发送模板消息失败：' . $result['errmsg']);
        }
    }

    /**
     * 发送分工通知消息
     */
    public function sendAllocationNotification($openid, $allocationData)
    {
        // 模板ID，需要在微信公众平台配置
        $templateId = config('wechat.template_id.allocation') ?: 'your_template_id_here';
        
        $data = [
            'first' => [
                'value' => '您有新的分工任务',
                'color' => '#173177'
            ],
            'keyword1' => [
                'value' => $allocationData['order_no'],
                'color' => '#173177'
            ],
            'keyword2' => [
                'value' => $allocationData['product_name'] . ' - ' . $allocationData['model_name'],
                'color' => '#173177'
            ],
            'keyword3' => [
                'value' => $allocationData['process_name'],
                'color' => '#173177'
            ],
            'keyword4' => [
                'value' => $allocationData['quantity'] . ' (' . $allocationData['work_type_text'] . ')',
                'color' => '#173177'
            ],
            'keyword5' => [
                'value' => date('Y-m-d H:i:s'),
                'color' => '#173177'
            ],
            'remark' => [
                'value' => '请及时查看并完成分工任务',
                'color' => '#173177'
            ]
        ];
        
        // 小程序页面路径
        $miniprogram = [
            'appid' => config('wechat.miniprogram.appid') ?: '',
            'pagepath' => 'pages/tasks/tasks'
        ];
        
        return $this->sendTemplateMessage($openid, $templateId, $data, '', $miniprogram);
    }

    /**
     * 发送审核结果通知
     */
    public function sendAuditNotification($openid, $auditData)
    {
        $templateId = config('wechat.template_id.audit') ?: 'your_audit_template_id_here';
        
        $statusText = $auditData['status'] == 1 ? '审核通过' : '审核不通过';
        $statusColor = $auditData['status'] == 1 ? '#00ff00' : '#ff0000';
        
        $data = [
            'first' => [
                'value' => '您的报工已审核完成',
                'color' => '#173177'
            ],
            'keyword1' => [
                'value' => $auditData['order_no'],
                'color' => '#173177'
            ],
            'keyword2' => [
                'value' => $auditData['product_name'],
                'color' => '#173177'
            ],
            'keyword3' => [
                'value' => $statusText,
                'color' => $statusColor
            ],
            'keyword4' => [
                'value' => $auditData['quantity'],
                'color' => '#173177'
            ],
            'keyword5' => [
                'value' => date('Y-m-d H:i:s'),
                'color' => '#173177'
            ],
            'remark' => [
                'value' => $auditData['status'] == 1 ? '恭喜您，报工审核通过！' : '请查看审核意见并重新提交',
                'color' => $statusColor
            ]
        ];
        
        $miniprogram = [
            'appid' => config('wechat.miniprogram.appid') ?: '',
            'pagepath' => 'pages/records/records'
        ];
        
        return $this->sendTemplateMessage($openid, $templateId, $data, '', $miniprogram);
    }

    /**
     * 发送系统通知消息
     */
    public function sendSystemNotification($openid, $systemData)
    {
        $templateId = config('wechat.template_id.system') ?: 'your_system_template_id_here';
        
        $data = [
            'first' => [
                'value' => $systemData['title'] ?? '系统通知',
                'color' => '#173177'
            ],
            'keyword1' => [
                'value' => $systemData['content'] ?? '',
                'color' => '#173177'
            ],
            'keyword2' => [
                'value' => $systemData['time'] ?? date('Y-m-d H:i:s'),
                'color' => '#173177'
            ],
            'keyword3' => [
                'value' => $systemData['remark'] ?? '',
                'color' => '#173177'
            ],
            'remark' => [
                'value' => '请及时查看系统通知',
                'color' => '#173177'
            ]
        ];
        
        $miniprogram = [
            'appid' => config('wechat.miniprogram.appid') ?: '',
            'pagepath' => 'pages/messages/messages'
        ];
        
        return $this->sendTemplateMessage($openid, $templateId, $data, '', $miniprogram);
    }

    /**
     * HTTP GET请求
     */
    protected function httpGet($url)
    {
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
        curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
        curl_setopt($ch, CURLOPT_TIMEOUT, 30);
        
        $response = curl_exec($ch);
        curl_close($ch);
        
        return $response;
    }

    /**
     * HTTP POST请求
     */
    protected function httpPost($url, $data)
    {
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_POST, true);
        curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
        curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
        curl_setopt($ch, CURLOPT_TIMEOUT, 30);
        curl_setopt($ch, CURLOPT_HTTPHEADER, [
            'Content-Type: application/json',
            'Content-Length: ' . strlen($data)
        ]);
        
        $response = curl_exec($ch);
        curl_close($ch);
        
        return $response;
    }
}
